package com.lilosoft.core.filter;

import com.lilosoft.core.cache.JedisRepository;
import com.lilosoft.core.utils.RenderUtil;
import com.lilosoft.core.utils.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * 本地权限鉴权验证过
 *
 * @author qiusheng
 * @version 2018-05-25
 */
@Component
@WebFilter(urlPatterns = "/*", filterName = "localAuthFilter")
public class LocalAuthFilter implements Filter {

    private final Log logger = LogFactory.getLog(this.getClass());

    @Value("${gsip.auth-open}")
    private boolean isOpenauth;

    @Autowired
    private JedisRepository jedis;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (!isOpenauth) {
            chain.doFilter(request, response);
            return;
        }

        if (StringUtils.urlIsMatches(Arrays.asList("/OauthUser/thirdPartyAuthorize"
                ,"/swagger-ui.*"
                ,"/webjars/springfox-swagger-ui/*"
                ,"/swagger-resources/*"
                ,"/v2/*"
                ,"/swagger-resources/*"
                , "/static/*"
                ), request.getServletPath())) {
            chain.doFilter(request, response);
            return;
        }

        String token = request.getHeader("access-token");
        if (StringUtils.isEmpty(token)) {
            RenderUtil.renderError(response, "认证token验证失败", 403);
            return;
        }
        if (jedis.exists(0, token)) {
            chain.doFilter(request, response);
            return;
        }else{
            RenderUtil.renderError(response, "认证token验证失败", 403);
            return;
        }
    }


}
